import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/login.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/login/register.vue')
    },
    {
      path: '/',
      name: 'tabPage',
      component: () => import('@/views/tab-pages/index.vue'),
      redirect: 'home',
      children: [
        {
          path: 'home',
          name: 'home',
          component: () => import('@/views/tab-pages/home.vue')
        },
        {
          path: 'article',
          name: 'article',
          component: () => import('@/views/tab-pages/article.vue')
        },
        {
          path: 'notice',
          name: 'notice',
          component: () => import('@/views/tab-pages/notice.vue')
        },
        {
          path: 'user',
          name: 'user',
          component: () => import('@/views/tab-pages/user.vue')
        }
      ]
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('@/views/home-pages/search.vue')
    }
  ]
})

import { useUserStore } from '@/stores/index'

const whiteList = ['login', 'register', '404']

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // to 代表即将到达的路由
  // from 即将离开的页面
  // next 函数 是否放行，应该放行到那里
  if (!whiteList.includes(to.name as string)) {
    const userStore = useUserStore()
    if (userStore.token) {
      next()
    } else {
      next('/login')
    }
    return
  }
  next()
})

export default router
